package com.jufa_3.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jufa_3.common.R;
import com.jufa_3.common.RequestTool;
import com.jufa_3.common.WeiChat;
import com.jufa_3.dto.Login;
import com.jufa_3.entity.*;
import com.jufa_3.mapper.ChargeRecordMapper;
import com.jufa_3.mapper.ComboOrderMapper;
import com.jufa_3.service.ComboOrderService;
import com.jufa_3.service.LoginInfoService;
import com.jufa_3.service.OpinionService;
import com.jufa_3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import static com.jufa_3.common.WeiChat.getToken;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private StringRedisTemplate srt;

    @Autowired
    private UserService userService;

    @Autowired
    private ComboOrderService comboOrderService;

    @Autowired
    private LoginInfoService loginInfoService;

    @Autowired
    private ChargeRecordMapper chargeRecordMapper;

    @Autowired
    private ComboOrderMapper comboOrderMapper;

    @Autowired
    private OpinionService opinionService;

    @GetMapping("/getLP")
    public R<Object> getLP() {
        return R.success(getToken("Adm123", "Adm"));
    }

    @GetMapping("/getParams")
    public R<Object> getParams() {
        JSONObject returnParams = new JSONObject();
        returnParams.put("newUserPrice", redisTemplate.opsForValue().get("newUserPrice"));
        returnParams.put("pullUserPrice", redisTemplate.opsForValue().get("pullUserPrice"));
        returnParams.put("checked", Boolean.parseBoolean(redisTemplate.opsForValue().get("checked").toString()));
        returnParams.put("contect", redisTemplate.opsForValue().get("contect"));
        return R.success(returnParams);
    }

    @GetMapping("getOpinions")
    public R<JSONObject> getUserOpinions(Opinion opinion, Integer pageSize, Integer pageNum) {
        // 构建查询
        LambdaQueryWrapper<Opinion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(opinion.getOpenId()), Opinion::getOpenId, opinion.getOpenId()).
                like(StringUtils.isNotEmpty(opinion.getRelation()), Opinion::getRelation, opinion.getRelation()).
                like(StringUtils.isNotEmpty(opinion.getName()), Opinion::getName, opinion.getName());
        JSONObject resultJs = new JSONObject();
        resultJs.put("total", opinionService.count(queryWrapper));
        pageNum--;
        queryWrapper.orderByDesc(Opinion::getCreateTime).last("limit " + pageSize * pageNum + "," + pageSize);
        resultJs.put("records", opinionService.list(queryWrapper));
        return R.success(resultJs);
    }

    @GetMapping("/updataParam")
    public R<Object> updataParam(String key, String param) {
        try {
            if ("true".equals(param) || "false".equals(param)) {
                redisTemplate.opsForValue().set(key, Boolean.parseBoolean(param));
            } else {
                srt.opsForValue().set(key, param);
            }
            return R.success(null);
        } catch (Exception e) {
            return R.error(4024, "操作失败");
        }
    }

    @GetMapping("/getUsers")
    public R<Object> getUserOpinions(User user, Integer pageNum, Integer pageSize) {
        // 构建查询
        List<User> users = userService.lambdaQuery()
                .like(StringUtils.isNotEmpty(user.getOpenId()), User::getOpenId, user.getOpenId())
                .like(StringUtils.isNotEmpty(user.getMobile()), User::getMobile, user.getMobile())
                .orderByDesc(User::getCreatedTime)
                .last("limit " + pageSize * --pageNum + "," + pageSize).list();
        List<UserAndCombos> list = new ArrayList();
        for (User u : users) {
            list.add(new UserAndCombos(u, comboOrderService.lambdaQuery().eq(ComboOrder::getOpenId, u.getOpenId()).eq(ComboOrder::getEnable, "1").list()));
        }
        return R.success(list);
    }


    /**
     * 获取拉取用户
     * @return
     */
    @GetMapping("/getPullUser")
    public R<PullNewUser> getPullUser(String source) {
        List<User> us = userService.lambdaQuery().eq(User::getSource, source).list();
        for (User u : us) {
            u.setMobile("***" + u.getMobile().substring(7));
        }
        Float sumPrice = comboOrderMapper.sumPrice(source);
        PullNewUser pullNewUser = new PullNewUser(us, sumPrice);
        return R.success(pullNewUser);
    }

    @GetMapping("/getChec")
    public R<Object> getChec() {
        return R.success(Boolean.parseBoolean(srt.opsForValue().get("checked")));
    }

    @GetMapping("/getContect")
    public R<Object> getContect() {
        return R.success(redisTemplate.opsForValue().get("contect").toString());
    }


    /**
     * 新用户微信授权注册
     *
     * @param request
     * @return
     */
    @GetMapping("/weichatRegister")
    public R<Object> weichatRegister(Login login, HttpServletRequest request) {
        login.setIP(RequestTool.getIpAddress(request));
        // IP 城市
        // login.setCity();
        User user = userService.addUserAndRecord(login);
        return R.success(user);
    }

    /**
     * 发送验证码
     *
     * @param phoneNum
     * @return
     * @throws Exception
     */
    @GetMapping("/sendVerifyCode")
    public R<String> sendVerifyCode(@RequestParam String phoneNum) throws Exception {
        String code = WeiChat.generateValidateCode(4).toString();  //生成随机的4位验证码
        log.info("向" + phoneNum + "发送验证码：" + code);
//        SendSmsResponseBody body = SMSUtils.sendMessage(phoneNum, code);            //调用阿里云提供的短信服务API完成短信发送
//        if ("OK".equals(body.getCode())) {
//            redisTemplate.opsForValue().set(phoneNum, code, 5, TimeUnit.MINUTES);
            return R.success(null);
//        } else {
//            return R.error(4003, "获取验证码失败");
//        }
    }

    /**
     * 新用户验证手机号注册
     *
     * @param request
     * @return
     */
    @GetMapping("/verifyCodeRegister")
    public R<Object> verifyCodeRegister(Login login, HttpServletRequest request) {
        login.setIP(RequestTool.getIpAddress(request));
        // IP 城市
        // login.setCity();
        R<Object> userR = userService.byVerifyCodeCheckRegister(login);
        return userR;
    }

    /**
     * 登陆
     *
     * @param request
     * @return
     */
    @GetMapping("/login")
    public R<Object> login(HttpServletRequest request) {
        String openid = request.getParameter("openid");
        if (StringUtils.isEmpty(openid)) {
            String loginCode = request.getParameter("loginCode");
            openid = WeiChat.getUserOpenId(loginCode).getString("openid");
        }
        if (StringUtils.isNotEmpty(openid)) {
            User user = userService.lambdaQuery().eq(User::getOpenId, openid).one();
            if (user != null) {
                String ipAddress = RequestTool.getIpAddress(request);
                // IP 城市
                // login.setCity();
                // 增设登陆记录
                loginInfoService.save(new LoginInfo(openid, LocalDateTime.now(), ipAddress, "未启用"));
                user.setToken(getToken(openid, "user"));
                return R.success(user);
            } else {
                JSONObject returnJs = new JSONObject();
                returnJs.put("openId", openid);
                returnJs.put("token", getToken(openid, "user"));
                // 未查询到，放过去注册
                return R.success(1002, returnJs);
            }
        } else {
            // 返回错误信息
            return R.error(4001, "openid获取失败");
        }
    }

    @GetMapping("/getUserCount")
    public void getUserCount(HttpServletResponse response) throws IOException {
        List<Integer> statistics = chargeRecordMapper.statistics();
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String html = "<html>\n" +
                "<head>\n" +
                "</head>\n" +
                "<body>\n" +
                "  <div>\n" +
                "    <h1 align=\"center\">获取时间：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "</h1>\n" +
                "    <h1 align=\"center\">合计收款金额：" + statistics.get(0) + "</h1>\n" +
                "    <h1 align=\"center\">总注册量：" + statistics.get(1) + "</h1>\n" +
                "    <h1 align=\"center\">今日注册量：" + statistics.get(2) + "</h1>\n" +
                "    <h1 align=\"center\">source_1：" + statistics.get(3) + "</h1>\n" +
                "    <h1 align=\"center\">本月other_source：" + statistics.get(4) + "</h1>\n" +
                "  </div>\n" +
                "</body>\n" +
                "</html>\n";
        Document doc = Jsoup.parse(html);
        PrintWriter writer = response.getWriter();
        writer.println(doc.outerHtml());
        out.flush();
        out.close();
    }

}
